import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:travel/model/theme.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/ui/scroll_refresh_config.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class ThemeTourismController extends GetxController {
  RxString theme = '主题旅游'.obs;

  RxString search = ''.obs;

  RefreshController refreshController = RefreshController();

  RxList<ThemeTourismModel> pageList = RxList([]);

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      theme.value = Get.arguments['theme'];
    }
    initData();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 15) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '故宫博物馆',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 40,
        tags: ['可订明日', '随时退']));

    /// 完毕
    refreshController.loadComplete();
  }

  @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
  }

  void initData() {
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '故宫博物馆',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 40,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '八达岭长城',
        level: 5,
        point: 4.5,
        evaluate: 5687,
        distance: 1.5,
        price: 35,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '香山公园',
        level: 3,
        point: 4.3,
        evaluate: 3487,
        distance: 1.8,
        price: 20,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '白塔寺',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: -1,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '湖广会馆',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: -1,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '北京古代建筑博物管',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 0,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '北京杜莎夫人蜡像馆',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 90,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '中国国家博物管',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: -1,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '天安门广场',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 0,
        tags: ['可订明日', '随时退']));
    pageList.add(ThemeTourismModel(
        imgUrl:
            'https://img2.baidu.com/it/u=614279430,1420774946&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        name: '史家胡同博物馆',
        level: 5,
        point: 4.6,
        evaluate: 5487,
        distance: 1.2,
        price: 0,
        tags: ['可订明日', '随时退']));
  }
}

class ThemeTourismView extends GetView<ThemeTourismController> {
  const ThemeTourismView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.white,
            leading: InkWell(
              onTap: () {
                Get.back();
              },
              child: Icon(
                Icons.arrow_back_ios,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                size: 20.w,
              ),
            ),
            leadingWidth: 40.w,
            title: Text(
              controller.theme.value,
              style: StylesUtils.customTextStyle(fontSize: 18.sp, color: ColorsUtils.color0000),
            ),
            centerTitle: true,
            bottom: bottom,
            systemOverlayStyle: SystemUiOverlayStyle.dark,
            elevation: 0,

            /// 关闭滚动渐变
            scrolledUnderElevation: 0,
            // surfaceTintColor: Colors.transparent,
            // forceMaterialTransparency: true,
          ),
          body: scrollRefreshConfig(context),
        ));
  }

  Widget scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  PreferredSize get bottom {
    return PreferredSize(
      preferredSize: Size.fromHeight(40.h),
      child: Container(
        height: 40.h,
        padding: EdgeInsets.only(bottom: 5.h, left: 10.w, right: 10.w),
        child: TextField(
          controller: ToolsUtils.editingController(controller.search.value),
          cursorWidth: 2.0,
          cursorRadius: const Radius.circular(2),
          cursorColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
          style: StylesUtils.customTextStyle(fontSize: 15.sp, color: ColorsUtils.color3333),
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search_sharp, size: 20.sp),
            prefixIconColor: Colors.black54,
            prefixIconConstraints: BoxConstraints.expand(width: 40.w),
            border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(18.h),
                borderSide:
                    BorderSide(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorE4e4))),
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(18.h),
                borderSide:
                    BorderSide(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorE4e4))),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(18.h),
                borderSide:
                    BorderSide(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorE4e4))),
            hintText: '搜索目的地/景点',
            contentPadding: EdgeInsets.symmetric(vertical: 12.h),
            isCollapsed: true,
            isDense: true,
            hintStyle: StylesUtils.customTextStyle(
              color: ColorsUtils.color9999,
            ),
          ),
          onChanged: (String keyword) {
            controller.search.value = keyword;
          },
        ),
      ),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        var row = controller.pageList[index];
        return InkWell(
          onTap: () {
            Get.toNamed(RoutePath.attractions, arguments: {'model': row});
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            decoration: const BoxDecoration(color: Colors.white),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 120.w,
                  height: 120.w,
                  alignment: Alignment.topLeft,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.w),
                    child: CachedNetworkImage(
                      imageUrl: row.imgUrl,
                      alignment: Alignment.topLeft,
                      fit: BoxFit.cover,
                      width: 120.w,
                      height: 120.w,
                      placeholder: (context, url) => const CircularProgressIndicator(),
                    ),
                  ),
                ),
                Expanded(
                    child: Container(
                  padding: EdgeInsets.only(left: 10.w),
                  child: Column(
                    children: [
                      Container(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          row.name,
                          style: StylesUtils.customTextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w700,
                              color: ColorsUtils.color3333),
                        ),
                      ),
                      Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          child: Container(
                            constraints: BoxConstraints.tightFor(width: 24.w, height: 18.h),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                                borderRadius: BorderRadius.circular(3.w)),
                            child: Text(
                              '${row.level}A',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp),
                            ),
                          )),
                      Container(
                        alignment: Alignment.centerLeft,
                        child: Wrap(
                          spacing: 10.w,
                          crossAxisAlignment: WrapCrossAlignment.center,
                          children: [
                            Text(
                              '${row.point}分',
                              style: StylesUtils.customTextStyle(
                                  fontSize: 12.sp, color: ColorsUtils.color7979),
                            ),
                            Text(
                              '${row.evaluate}人评价',
                              style: StylesUtils.customTextStyle(
                                  fontSize: 12.sp, color: ColorsUtils.color7979),
                            )
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.symmetric(vertical: 5.w),
                        child: Text(
                          '距离您${row.distance}km',
                          style: StylesUtils.customTextStyle(
                              fontSize: 12.sp, color: ColorsUtils.color7979),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: Wrap(
                            spacing: 5.w,
                            crossAxisAlignment: WrapCrossAlignment.center,
                            children: row.tags.map((e) {
                              double width = ToolsUtils.calculateTextHeight(
                                  context, e, FontWeight.normal, 12.sp, 54.w, 1);
                              return Container(
                                height: 20,
                                constraints: BoxConstraints(maxWidth: width + 10),
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: ColorsUtils.parseColorFromHexString(
                                            ColorsUtils.colorB8cd)),
                                    borderRadius: BorderRadius.circular(3.w),
                                    color:
                                        ColorsUtils.parseColorFromHexString(ColorsUtils.colorF1f7)),
                                alignment: Alignment.center,
                                child: Text(
                                  e,
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 12.sp, color: ColorsUtils.color6799),
                                ),
                              );
                            }).toList(),
                          )),
                          Container(
                            alignment: Alignment.centerRight,
                            child: getChildPrice(row.price),
                          )
                        ],
                      )
                    ],
                  ),
                ))
              ],
            ),
          ),
        );
      },
      itemCount: controller.pageList.length,
      itemExtent: 136.h,
    );
  }

  Text getChildPrice(int price) {
    if (price < 0) {
      return Text(
        '免费预约',
        style: StylesUtils.customTextStyle(
          color: ColorsUtils.color6666,
        ),
      );
    }
    if (price == 0) {
      return Text(
        '免费',
        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
      );
    }
    return Text.rich(TextSpan(children: [
      TextSpan(
          text: '￥',
          style: StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.colorD900)),
      TextSpan(
          text: '$price',
          style: StylesUtils.customTextStyle(
              fontSize: 20.sp, fontWeight: FontWeight.w700, color: ColorsUtils.colorD900)),
      TextSpan(
          text: '起',
          style: StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.color7979))
    ]));
  }
}
